<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<script lang="tsx" setup>
import type { TreeOption } from 'naive-ui';
import { NButton, NPopconfirm } from 'naive-ui';
import { h, ref, toRefs } from 'vue';
import { Icon } from '@iconify/vue';
import { deptTreeSelect } from '@/service/api/system/user';
import { delPost, getPageList } from '@/service/api/system/post';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { useDict } from '@/utils/dict';
import SvgIcon from '@/components/custom/svg-icon.vue';
import DictTag from '@/components/custom/dict-tag.vue';
import type { PostVO } from '@/service/types/system';
import PostSearch from './components/post-search.vue';
import PostForm from './components/post-form.vue';
const { sys_normal_disable } = toRefs<any>(useDict('sys_normal_disable'));

const appStore = useAppStore();
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: getPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    postName: null,
    postCode: null,
    deptId: null,
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'postName',
      title: '岗位名称',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'postCode',
      title: '岗位编码',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'postSort',
      title: '排序',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      render: (row: PostVO) => {
        return <DictTag type="tag" value={row.status} dicts={sys_normal_disable.value} />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (row: PostVO) => {
        return (
          <div class="flex-center gap-15px">
            <NButton
              tag="a"
              type="primary"
              text
              size="small"
              onClick={() => {
                editor(row?.postId);
              }}
              v-slots={{
                icon: () => <SvgIcon icon="ant-design:edit-outlined" />
              }}
            ></NButton>
            <NPopconfirm
              onPositiveClick={() => {
                handleDelete(row.postId as number);
              }}
              onNegativeClick={() => {
                (window as any).$message.info('已取消删除');
              }}
            >
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton text tag="a" type="error" ghost size="small">
                    {{
                      icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        );
      }
    }
  ]
});

const { currentId, drawerVisible, operateType, handleAdd, customerEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, getData, 'postId');
const editor = (id: number | string) => {
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  customerEdit(id);
};
function renderPrefix() {
  return h(Icon, { icon: 'clarity:organization-line', class: 'font-size-4' });
}
const deptDataTree = ref([]);
// 请求部门树
const getDeptTreeList = () => {
  deptTreeSelect().then((res: any) => {
    deptDataTree.value = res?.data?.data;
  });
};
getDeptTreeList();
// 树节点点击事件
const nodeProps = ({ option }: { option: TreeOption }) => {
  return {
    onClick() {
      searchParams.deptId = option.id as number;
      getData();
    }
  };
};

const requestRemove = async (postId: number | number[]): Promise<boolean> => {
  const loadinginstance = (window as any).$message.loading('正在处理中');
  const { data, error } = await delPost(postId);
  loadinginstance.destroy();
  if (!error) {
    (window as any).$message.success(data?.msg);
    return Promise.resolve(true);
  }
  throw new Error('false');
};
const handleDelete = async (postId: number) => {
  const result = await requestRemove(postId as number);
  if (result) {
    onDeleted();
  }
};
const handleBatchDelete = async () => {
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定删除这些吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await requestRemove(checkedRowKeys.value as unknown as number[]);
      if (result) {
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NSplit direction="horizontal" :default-size="0.2" :resize-trigger-size="12" :min="0.2" :max="0.8">
      <template #1>
        <NCard
          title="组织列表"
          :bordered="false"
          size="small"
          class="lt-sm:overflow-aut h-100% min-h-500px flex-col-stretch sm:flex-1-hidden gap-16px overflow-hidden sm:h-full"
        >
          <NTree
            block-line
            :render-prefix="renderPrefix"
            :data="deptDataTree"
            key-field="id"
            label-field="label"
            :node-props="nodeProps"
            children-field="children"
          />
        </NCard>
      </template>
      <template #2>
        <div class="h-100% min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
          <PostSearch
            v-model:model="searchParams"
            :status="sys_normal_disable"
            @reset="resetSearchParams"
            @search="getData"
          />
          <NCard title="岗位管理" :bordered="false" size="small" class="sm:flex-1-hidden">
            <template #header-extra>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                @add="handleAdd"
                @delete="handleBatchDelete"
                @refresh="getData"
              />
            </template>
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns"
              :data="data"
              size="small"
              :flex-height="!appStore.isMobile"
              :scroll-x="962"
              :loading="loading"
              remote
              :row-key="(row: PostVO) => row.postId"
              :pagination="mobilePagination"
              class="sm:h-full"
            >
              <template #empty>
                <Empty />
              </template>
            </NDataTable>
          </NCard>
        </div>
      </template>
      <template #resize-trigger>
        <div class="h-100% flex justify-center flex-items-center">
          <SvgIcon class="color-white" icon="nimbus:arrows-horizontal" />
        </div>
      </template>
    </NSplit>
    <PostForm
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :sys-normal-disable="sys_normal_disable"
      :current-id="currentId"
      :depts="deptDataTree"
      @submitted="getData"
    />
  </div>
</template>

<style scoped></style>
